import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
} from 'react';
import { Select, Checkbox } from 'antd';
import type { FormInstance, SelectProps } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import type { CheckboxOptionType } from 'antd/es/checkbox';
import './selectCheckbox.scss';
const { Option } = Select;

type selfProps = SelectProps & {
  formInstance: FormInstance<any>;
  field: string;
};
export type SelectCheckRef = {
  setSelectCheckedValue: (values: CheckboxValueType[]) => void;
};
const SelectCheckbox: React.ForwardRefRenderFunction<
  SelectCheckRef,
  selfProps
> = ({ formInstance, options, field, ...restProps }, ref) => {
  const [checkAll, setCheckAll] = useState<boolean>(false);
  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>([]);
  const [indeterminate, setIndeterminate] = useState<boolean>(false);

  const selectChangeHandle = (value: string | number) => {
    setCheckedList([...checkedList, value]);
  };
  const unSelectChangeHandle = (value: string | number) => {
    let index = checkedList.findIndex(item => item === value);
    setCheckedList(checkedList.filter((item, i) => i !== index));
  };
  const clearCheckList = () => {
    setCheckedList([]);
  };
  useEffect(() => {
    setIndeterminate(
      !!checkedList.length &&
        checkedList.length < (options as DefaultOptionType[])?.length
    );
    setCheckAll(!!options?.length && checkedList.length === options.length);
    formInstance.setFieldsValue({
      [field]: checkedList,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [checkedList, options]);
  const setSelectCheckedValue = (values: CheckboxValueType[]) => {
    setCheckedList(values);
  };
  useImperativeHandle(ref, () => ({
    setSelectCheckedValue,
  }));
  return (
    <Select
      mode="multiple"
      allowClear
      style={{ width: '100%' }}
      placeholder="请选择"
      value={checkedList as any}
      onSelect={selectChangeHandle}
      onDeselect={unSelectChangeHandle}
      onClear={clearCheckList}
      {...restProps}
      dropdownRender={checkedAll => (
        <>
          <div>
            <Checkbox
              style={{
                width: '100%',
                height: '100%',
                padding: '5px 12px',
                boxSizing: 'border-box',
              }}
              checked={checkAll}
              indeterminate={indeterminate}
              onChange={e => {
                if (e.target.checked) {
                  setCheckAll(true);
                  let result = options?.map(
                    item => (item as CheckboxOptionType).value
                  ) as CheckboxValueType[];
                  setCheckedList(result);
                } else {
                  setCheckAll(false);
                  clearCheckList();
                }
              }}>
              全选
            </Checkbox>
          </div>
          {checkedAll}
        </>
      )}
      optionLabelProp="label">
      {options?.map(item => {
        return (
          <Option
            value={item.value}
            label={item.label}
            key={item.value}
            className="checkbox-select"
            style={{ padding: 0 }}>
            <div
              style={{
                position: 'absolute',
                width: '100%',
                height: '100%',
                padding: '5px 12px',
                boxSizing: 'border-box',
              }}></div>
            <Checkbox
              style={{
                width: '100%',
                height: '100%',
                padding: '5px 12px',
                boxSizing: 'border-box',
              }}
              checked={checkedList?.includes(item.value as string)}>
              {item.label}
            </Checkbox>
          </Option>
        );
      })}
    </Select>
  );
};
export default forwardRef(SelectCheckbox);
